package cn.crawler.app.task.commons.ext.quartz.job;

import cn.crawler.app.crown.modules.models.CrownConfig;
import cn.crawler.app.crown.modules.services.CrownConfigService;
import cn.crawler.app.crown.modules.services.pl.PdHalfResolverService;
import cn.crawler.app.crown.modules.services.pl.PdResolverService;
import cn.crawler.app.crown.modules.services.pl.TResolverService;
import cn.crawler.app.sys.modules.services.SysTaskService;
import cn.crawler.framework.util.ThreadUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.quartz.Job;
import org.quartz.JobExecutionContext;

/**
 * 获取全场、半场波胆、全场总入球任务
 */
@IocBean
public class CrownJobMatch implements Job {

    @Inject
    @Reference(retries = 0, timeout = 500000)
    private CrownConfigService crownConfigService;

    @Inject
    @Reference(retries = 0, timeout = 500000)
    private PdResolverService pd;

    @Inject
    @Reference(retries = 0, timeout = 500000)
    private PdHalfResolverService pdHalf;

    @Inject
    @Reference(retries = 0, timeout = 500000)
    private TResolverService t;

    @Inject
    @Reference
    private SysTaskService sysTaskService;

    private static final Log log = Logs.get();

    @Override
    public void execute(JobExecutionContext context) {
        // 获取一个爬虫账号 线程安全
        CrownConfig crownConfig = crownConfigService.syncOne("获取全场、半场波胆、全场总入球任务");
        if (null != crownConfig) {
            log.info("准备开始任务:" + crownConfig);
            ThreadUtil.execute(new Runnable() {
                @Override
                public void run() {
                    crawler(crownConfig, context);
                }
            });
        }
        String taskId = context.getJobDetail().getKey().getName();
        sysTaskService.update(Chain.make("exeAt", (int) (System.currentTimeMillis() / 1000))
                .add("exeResult", "执行成功"), Cnd.where("id", "=", taskId));
    }

    private void crawler(CrownConfig crownConfig, JobExecutionContext jobExecutionContext) {
        try {
            // 全场波胆
            pd.future(crownConfig);
            pd.browse(crownConfig);
            // 半场波胆
            pdHalf.future(crownConfig);
            pdHalf.browse(crownConfig);
            // 全场总入球
            t.future(crownConfig);
            t.browse(crownConfig);
        } catch (Exception e) {
            log.error("爬虫定时任务异常" + e.getMessage());
        } finally {
            // 获取账号，判断是否为空，以防账号已经被清除
            crownConfigService.release(crownConfig);
        }
    }
}
